/*
 * @(#)EmailRuleEngineHandle.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.core;

import java.sql.Connection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.rules.RuleOperationConstant;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.bean.UserRole;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;
import com.dcivision.workflow.bean.WorkflowRecord;
import com.dcivision.workflow.dao.WorkflowRecordDAObject;

/**
 * <p> Class Name: EmailRuleEngineHandle</p>
 * <p> Decription: This class is when edit and new rule, offer some method.</p>
 * 
 * 
 * @author        Tony Chen
 * @company       DCIVision Limited
 * @creation date 05/09/2005
 * @version       $Revision: 1.6 $
 */
public class EmailRuleEngineHandle {
  protected Log log = LogFactory.getLog(this.getClass().getName());
  
	public EmailRuleEngineHandle() {	
	}
  
  /**
   * get Session Container
   * @return
   */
  public SessionContainer getSessionContainer() {
    SessionContainer sessionCon = new SessionContainer();
   
    UserRecord tmpUserRecord = new UserRecord();
    tmpUserRecord.setID(new Integer(0));
    sessionCon.setUserRecord(tmpUserRecord);
    sessionCon.setUserIPAddress("127.0.0.1");
    
    return sessionCon;
  }
  
  /**
   * get folder path by parentID
   * @param rootID
   * @param parentID
   * @return
   */
  public String getFolderPath(String rootID, String parentID){
    String folderPath = "";
    
    Connection dbConn = null;    
    try{      
      dbConn = DataSourceFactory.getConnection();
      DocumentRetrievalManager documentRetrievalManager = new DocumentRetrievalManager(this.getSessionContainer(), dbConn);      
      folderPath = documentRetrievalManager.getLocationPath(new Integer(parentID)); 
    } catch (ApplicationException appEx) {
      log.debug(" Application Exception :", appEx);
      log.error(appEx);
    } catch (Exception e) {
      log.error(e);
    } finally {
      try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }   
         
    return folderPath;
  }
  
  /**
   * get user names
   * @param userIDs
   * @return
   */
  private String getUserNames(String userIDs){
    if (Utility.isEmpty(userIDs)) {
      return "";
    }
    String userNames = "";    
    Connection dbConn = null;    
    try {
      dbConn = DataSourceFactory.getConnection();
    	UserRecordDAObject userRecordDAO = new UserRecordDAObject(this.getSessionContainer(), dbConn);
      String[] userIDArr = TextUtility.splitString(userIDs, RuleOperationConstant.SPLIT_COMMA);
      for (int i = 0; i < userIDArr.length; i++) {
        UserRecord userRecord = (UserRecord)userRecordDAO.getObjectByID(new Integer(userIDArr[i]));  
        if (i > 0) {
          userNames += RuleOperationConstant.SPLIT_BIAS;
        }
        userNames += userRecord.getFullName();
      }
      
    }catch (ApplicationException appEx) {
    	log.debug(" Application Exception :", appEx);
    	log.error(appEx);
    } catch (Exception e) {    	
    	log.error(e);
    } finally {
    	try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }       
    return userNames;
  }
  
  /**
   * get user groups 
   * @param groupIDs
   * @return
   */
  private String getUserGroups(String groupIDs){
    if (Utility.isEmpty(groupIDs)) {
      return "";
    }
    String groupNames = "";
    Connection dbConn = null;    
    try {
      dbConn = DataSourceFactory.getConnection();
      UserGroupDAObject userGroupDAO = new UserGroupDAObject(this.getSessionContainer(), dbConn);
      String[] groupIDArr = TextUtility.splitString(groupIDs, RuleOperationConstant.SPLIT_COMMA);
      for (int i = 0; i < groupIDArr.length; i++) {
        UserGroup userGroup = (UserGroup)userGroupDAO.getObjectByID(new Integer(groupIDArr[i]));  
        if (i > 0) {
          groupNames += RuleOperationConstant.SPLIT_BIAS;
        }
        groupNames += userGroup.getGroupName();
      }
      
    }catch (ApplicationException appEx) {
      log.debug(" Application Exception :", appEx);
      log.error(appEx);
    } catch (Exception e) {
      log.error(e);
    } finally {
      try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }       
    return groupNames;
  }
  
  /**
   * get role names
   * @param roleIDs
   * @return
   */
  private String getRoleNames(String roleIDs){
    if (Utility.isEmpty(roleIDs)) {
      return "";
    }
    String roleNames = "";
    Connection dbConn = null;    
    try {
      dbConn = DataSourceFactory.getConnection();
      UserRoleDAObject userRoleDAO = new UserRoleDAObject(this.getSessionContainer(), dbConn);
      String[] roleIDArr = TextUtility.splitString(roleIDs, RuleOperationConstant.SPLIT_COMMA);
      for (int i = 0; i < roleIDArr.length; i++) {
        UserRole userRole = (UserRole)userRoleDAO.getObjectByID(new Integer(roleIDArr[i]));  
        if (i > 0) {
          roleNames += RuleOperationConstant.SPLIT_BIAS;
        }
        roleNames += userRole.getRoleName();
      }
      
    }catch (ApplicationException appEx) {
      log.debug(" Application Exception :", appEx);
      log.error(appEx);
    } catch (Exception e) {
      log.error(e);
    } finally {
      try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }       
    return roleNames;
  }
  
  /**
   * get user picker display string 
   * @param showValue
   * @return
   */
  public String getUserPickerString(String showValue){
    
    String userIDs = "";
    String groupIDs = "";
    String roleIDs = "";
    
    //spilt userIDs , groupIDs , roleIDs
    if(!Utility.isEmpty(showValue)){
      String[] tmpArr = TextUtility.splitString(showValue, RuleOperationConstant.SPLIT_COMMA);
      for(int i = 0; i < tmpArr.length; i++){
        if(tmpArr[i].indexOf("U") > -1){
          if(!Utility.isEmpty(userIDs)){
            userIDs += RuleOperationConstant.SPLIT_COMMA;
          }
          userIDs += (tmpArr[i]).substring(2);//U:1
        
        } else if(tmpArr[i].indexOf("G") > -1){
          if(!Utility.isEmpty(groupIDs)){
            groupIDs += RuleOperationConstant.SPLIT_COMMA;
          }
          groupIDs += (tmpArr[i]).substring(2);//G:1
          
        } else if(tmpArr[i].indexOf("R") > -1){
          if(!Utility.isEmpty(roleIDs)){
            roleIDs += RuleOperationConstant.SPLIT_COMMA;
          }
          roleIDs += (tmpArr[i]).substring(2);//R:1
          
        }
      }
    }
    
    String str = "";
    str += this.getUserNames(userIDs);
    
    String groupNames = this.getUserGroups(groupIDs);
    String roleNames = this.getRoleNames(roleIDs);
    
    if (!Utility.isEmpty(str) && !Utility.isEmpty(groupNames)) {
      str += RuleOperationConstant.SPLIT_COMMA;
    }
    str += groupNames;
    
    
    if (!Utility.isEmpty(str) && !Utility.isEmpty(roleNames)) {
      str += RuleOperationConstant.SPLIT_COMMA;
    }     
    str += roleNames;
    
    return str;
  }
  
  /**
   * get workflow code by workflow ID
   * @param workflowRecordID
   * @return String
   */
  public String getWorfklowCodeByWorkflowRecordID(Integer workflowRecordID) {
    String workflowCode = "";
    Connection dbConn = null;    
    try {
      dbConn = DataSourceFactory.getConnection();
      WorkflowRecordDAObject workflowRecordDAO = new WorkflowRecordDAObject(this.getSessionContainer(), dbConn);
      WorkflowRecord workflowRecord = (WorkflowRecord)workflowRecordDAO.getObjectByID(workflowRecordID);
      workflowCode = workflowRecord.getWorkflowCode() + " ( " + workflowRecord.getWorkflowVersion() + " )";
    }catch (ApplicationException appEx) {
      log.debug(" Application Exception :", appEx);
      log.error(appEx);
    } catch (Exception e) {
      log.error(e);
    } finally {
      try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }       
    return workflowCode;
  }
  
  /**
   * get full name by user record DI
   * @param userRecordID a user record ID
   * @return String full name of a user
   */
  public String getUserFullNameByUserID (Integer userRecordID) {
    String fullName = "";
    Connection dbConn = null;    
    try {
      dbConn = DataSourceFactory.getConnection();
      UserRecordDAObject userRecordDAO = new UserRecordDAObject(this.getSessionContainer(), dbConn);
      UserRecord userRecord = (UserRecord)userRecordDAO.getObjectByID(userRecordID);
      fullName = userRecord.getFullName();
    }catch (ApplicationException appEx) {
      log.debug(" Application Exception :", appEx);
      log.error(appEx);
    } catch (Exception e) {
      log.error(e);
    } finally {
      try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }       
    return fullName;
  }
  
  /**
   * check execute permission by workflow record ID and user record ID
   * @param workflowRecordID
   * @param userRecordID
   * @return boolean
   */
  public boolean checkPermissionByWorkflowRecordIDUserRecordID(Integer workflowRecordID, Integer userRecordID){
    
    Connection dbConn = null;    
    try {
      dbConn = DataSourceFactory.getConnection();
      WorkflowRecordDAObject workflowRecordDAO = new WorkflowRecordDAObject(this.getSessionContainer(), dbConn);
      
      boolean permission = false;
      //check deny execute => w
      permission = workflowRecordDAO.checkPermissionByWorkflowRecordIDUserRecordID(workflowRecordID, userRecordID, "w");
      if (permission) {
        return false;
      } else {
        //check allow execute => W
        return workflowRecordDAO.checkPermissionByWorkflowRecordIDUserRecordID(workflowRecordID, userRecordID, "W");  
      }
      
    }catch (ApplicationException appEx) {
      log.debug(" Application Exception :", appEx);
      log.error(appEx);
    } catch (Exception e) {
      log.error(e);
    } finally {
      try { dbConn.close(); } catch (Exception ignore) {} finally { dbConn = null; }
    }       
    return false;
  }
  
  /**
   * get user picker display string 
   * @param userIDs
   * @param groupIDs
   * @param roleIDs
   * @return
   */  
  public String getUserPickerString(String userIDs, String groupIDs, String roleIDs){
    
    String str = "";
    str += this.getUserNames(userIDs);
    
    String groupNames = this.getUserGroups(groupIDs);
    String roleNames = this.getRoleNames(roleIDs);
    
    if (!Utility.isEmpty(str) && !Utility.isEmpty(groupNames)) {
      str += RuleOperationConstant.SPLIT_COMMA;
    }
    str += groupNames;
    
    
    if (!Utility.isEmpty(str) && !Utility.isEmpty(roleNames)) {
      str += RuleOperationConstant.SPLIT_COMMA;
    }     
    str += roleNames;
    
    return str;
  }
}
